<script setup lang="ts">
import { reactive, onBeforeMount, toRaw, ref, watch, computed } from 'vue'
import {
  FormItemRule,
  useMessage,
  NModal,
  NButton,
  NFormItem,
  NInput,
  NInputNumber,
  NSwitch,
  NDataTable
} from 'naive-ui'
import StationService from '@/services/station.service'
import UserService from '@/services/user.service'
import { StationMap } from '@/pages/design/service/item/read.type'

interface delData {
  id: string
}

const stationService = new StationService()
const uesrService = new UserService()
const message = useMessage()
/** 表单数据验证 */
const serviceData = computed(() => stationService.stations.value)
/** 表单数据验证 */
const rules = [
  {
    required: true,
    message: '请输入',
    trigger: ['input', 'blur']
  },
  {
    required: true,
    validator (_rule: FormItemRule) {
      if (!data.params.slice(1)[1].value) {
        return new Error('请输入中心坐标')
      } else if (data.params.slice(1)[1].value as unknown as number < 0) {
        return new Error('请输入正整数')
      }
      return data.params.slice(1)[1].valiPass = true
    },
    trigger: ['input', 'blur']
  },
  {
    required: true,
    validator (_rule: FormItemRule) {
      if (!data.params.slice(1)[2].value) {
        return new Error('请输入车站长度')
      } else if (data.params.slice(1)[2].value as unknown as number < 0) {
        return new Error('请输入正整数')
      }
      return data.params.slice(1)[2].valiPass = true
    },
    trigger: ['input', 'blur']
  },
  {
    required: true,
    validator (_rule: FormItemRule) {
      if (!data.params.slice(1)[3].value) {
        return new Error('请输入车站名')
      }
      return data.params.slice(1)[3].valiPass = true
    },
    trigger: ['input', 'blur']
  }
]
const showModal = ref(false)
const data = reactive({
  title: '车站',
  name: 'stations',
  params: [
    {
      title: '#',
      key: 'key',
      render: (_: Any, index: number) => {
        return `${index + 1}`
      },
      width: 40
    },
    {
      key: 'id',
      title: 'id',
      value: '',
      entryType: 'string'
    },
    {
      key: 'center',
      title: '中心',
      value: null,
      valiPass: false,
      entryType: 'number'
    },
    {
      key: 'length',
      title: '长度',
      value: null,
      valiPass: false,
      entryType: 'number'
    },
    {
      key: 'name',
      title: '站名',
      value: '',
      valiPass: false,
      entryType: 'string'
    }
  ]
})
/** 是否选中右侧表格栏 判断左侧按钮是添加/修改  */
const tableRowChecked = ref(false)
/** switch不分输入 */
function handleChange (e: string) {
}

function resetInp () {
  (data.params).slice(1).forEach(item => {
    item.value = null
  })
  tableRowChecked.value = false
  uesrService.getOnlyId().then((res) => {
    if (res.success) {
      data.params.find((e) =>
        toRaw(e).title === 'id'
      )!.value = JSON.parse(JSON.stringify(res.data.id.toString(16))).toUpperCase()
    }
  })
}

/** 点击添加按钮 */
async function onAddClick () {
  let _obj = reactive<StationMap>({
    id: '',
    name: '',
    center: 0,
    length: 0
  })
  for (const { key, value } of data.params.slice(1)) {
    if (key === 'id') {
      _obj[key] = JSON.parse(JSON.stringify(parseInt(value as string, 16).toString(10)))
    } else if (key === 'name') {
      _obj[key] = value as string
    } else {
      _obj[key] = JSON.parse(JSON.stringify(parseInt(value as string).toString(10)))
    }
  }

  let res = await stationService.add(toRaw(_obj))
  if (!res?.success) {
    message.error(res?.message)
    return
  }
  if (res?.success) {
    message.success('新增车站成功')
    resetInp()
  }
}

/** 点击tab单行数据回填显示修改按钮 */
function rowProps (row: Any) {
  return {
    style: 'cursor: pointer;',
    onClick: () => {
      tableRowChecked.value = true
      let _obj = toRaw(row)
      _obj[Symbol.iterator] = function () {
        return {
          next: function () {
            let objArr = Reflect.ownKeys(_obj)
            if (this.index < objArr.length - 1) {
              let key = objArr[this.index]
              this.index++
              return { value: _obj[key] }
            } else {
              return { done: true }
            }
          },
          index: 0
        }
      }
      data.params.forEach(item => {
        for (let itemTab in _obj) {
          if (item.key === itemTab) {
            if ('valiPass' in item) {
              item.valiPass = true
            }
            if (item.key === 'id') {
              item.value = JSON.parse(JSON.stringify(_obj[itemTab])) ? JSON.parse(JSON.stringify(_obj[itemTab])) : ''
            }
            item.value = JSON.parse(JSON.stringify(_obj[itemTab])) ? JSON.parse(JSON.stringify(_obj[itemTab])) : 0
            // item.value?.replace('"', '').replace('"', '')
          }
        }
      })
    }
  }
}
/** 点击修改 */
async function onChangeClick () {
  let _obj = reactive<StationMap>({
    id: '',
    name: '',
    center: 0,
    length: 0
  })
  for (const { key, value } of data.params.slice(1)) {
    if (key === 'id') {
      _obj[key] = JSON.parse(JSON.stringify(parseInt(value as string, 16).toString(10)))
    } else if (key === 'name') {
      _obj[key] = value as string
    } else {
      _obj[key] = JSON.parse(JSON.stringify(value))
    }
  }
  let res = await stationService.change(toRaw(_obj))
  if (!res?.success) {
    message.error(res?.message)
    return
  }
  if (res?.success) {
    message.success('修改车站成功')
    resetInp()
  }
}
/** 点击删除 */
function onDelClick () {
  showModal.value = true
}
async function deleteConfig () {
  let _obj = reactive<delData>({
    id: ''
  })
  for (const { key, value } of data.params.slice(1)) {
    if (key === 'id') {
      _obj[key] = JSON.parse(JSON.stringify(parseInt(value as string, 16).toString(10)))
    }
  }
  const res = await stationService.del({ id: `${toRaw(_obj).id}` })
  if (!res?.success) {
    message.error(res?.message)
  }
  if (res?.success) {
    message.success('删除车站成功')
    resetInp()
  }
}
/** 取消 清空表单数据 或清空表单旧&新增数据 */
function onClose () {
  resetInp()
}

function load () {
  uesrService.getOnlyId().then((res) => {
    if (res.success) {
      data.params.find((e) =>
        toRaw(e).title === 'id'
      )!.value = JSON.parse(JSON.stringify(res.data.id.toString(16))).toUpperCase()
    }
    stationService.load()
  })
}

/** 监听区段数据 同步更新道岔下拉框数据 */
watch(
  () => stationService.stations.value,
  (val) => {
    stationService.stationOption.value = []
    stationService.stations.value.forEach((item) => {
      stationService.stationOption.value.push(
        {
          value: JSON.parse(JSON.stringify(parseInt(item.id as string, 16).toString(10))),
          label: ` 中心坐标${item.center} 车站`
        }
      )
    })
  },
  {
    deep: true,
    immediate: true
  }
)

onBeforeMount(
  load
)
</script>

<template>
  <div class="data-module">
    <n-modal class="delete-modal" v-model:show="showModal" preset="dialog" title="删除" content="确定删除该配置吗?"
      positive-text="确认" negative-text="取消" @positive-click="deleteConfig" />
    <div class="left">
      <div class="top">
        <n-form-item v-for="(itemData, index) in data.params.slice(1)" :key="index" :label-width="66       "
          label-placement="left" label-align="right" :label="itemData.title" :rule="rules[index]">
          <n-input :disabled="itemData.title==='id'" v-if="itemData.key==='id'||itemData.key==='name'" v-model:value="itemData.value"  :placeholder="`请输入${itemData.title}`"/>
          <div v-else-if="itemData.entryType==='switch'" class="switch-btn">
            <div class="btn">
              <n-switch v-model:value="(itemData as Any).value" checked-value="1" unchecked-value="0"
                @update:value="handleChange" />
              <div class="status">{{itemData.value==='0'?'左线':'右线'}}</div>
            </div>
          </div>
          <n-input-number v-else-if="itemData.entryType==='number'" v-model:value="(itemData as Any).value" :show-button="false"  :precision="0"  :placeholder="`请输入${itemData.title}数据`"/>
        </n-form-item>
      </div>
      <div class="bottom">
        <n-button class="del" type="primary" @click="onClose">取消</n-button>
        <n-button class="add" type="primary" v-if="!tableRowChecked" @click="onAddClick">添加</n-button>
        <div class="click-tab" v-else>
          <n-button class="add" type="primary" @click="onDelClick">删除</n-button>
          <n-button class="change" type="primary" @click="onChangeClick">修改</n-button>
        </div>
      </div>
    </div>
    <div class="right">
      <div class="title">
        {{data.title}}记录
      </div>
      <n-data-table :bordered="true" :single-line="false" :columns="data.params" :data="serviceData" :max-height="400"
        :row-props="rowProps">
      </n-data-table>
    </div>
  </div>
</template>

<style scoped lang="less">
.data-module {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;

  .left {
    padding: 30px;
    // width:42.2vw;
    min-width: 810px;
    width: 810px;
    height: 502px;
    background: #18171D;
    border-radius: 10px;
    border: 1px solid #5A5A62;
    margin-right: 10px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
    justify-content: space-between;

    .top {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      justify-content: space-between;

      .switch-btn {
        display: flex;
        justify-content: start;
        width: 360px;
        height: 36px;
        align-items: center;

        .title {
          width: 60px;
          margin-right: auto;
          text-align: right;
          padding-right: 10px;
          box-sizing: border-box;
        }

        .btn {
          display: flex;
          justify-content: start;
          width: 300px !important;

          .status {
            margin-left: 5px;
          }
        }
      }

      :deep(.n-form-item) {
        width: 360px;
        height: 36px;
        margin-bottom: 30px;

        .n-input-wrapper {
          width: 300px !important;
          background: #25242B;
          border-radius: 4px;
          border: 1px solid #5A5A62;

        }

        .n-input-number {
          width: 294px !important;
          background: #25242B;
          border-radius: 4px;
          border: 1px solid #5A5A62;

        }
      }
    }

    .bottom {
      display: flex;
      flex-direction: row;
      justify-content: end;
      color: #fff;

      .n-button {
        width: 120px;
        height: 46px;
        background: #25242B;
        border-radius: 25px;
        border: 1px solid #5A5A62;
      }

      .add,
      .change {
        margin-left: 30px;
        width: 120px;
        height: 46px;
        background: rgba(190, 164, 255, 0.4);
        border-radius: 25px;
        border: 1px solid #8F83CB;
      }
    }

  }

  .right {
    height: 502px;
    flex: 1;
    // width: 54.7vw;
    min-width: 1020px;
    background: #18171D;
    border-radius: 10px;
    border: 1px solid #5A5A62;
    display: inline-block;
    padding: 10px;
    box-sizing: border-box;

    .title {
      margin-bottom: 10px;
    }

    :deep(.n-data-table) {

      .n-data-table-tr {
        height: 40px !important;

        .n-data-table-td,
        .n-data-table-th {
          padding: 8px 0 8px 18px;
          font-size: 14px;
        }
      }
    }

  }
}

:deep(.n-tabs-tab) {
  height: 40px;
  background: #18171D;
  border-radius: 4px;
  border: 1px solid #5A5A62;
  padding: 0 12px;
}
</style>
